import { Input } from 'antd';
import FormRender, { useForm } from 'form-render';
import { shallowEqual, useSelector } from 'react-redux';
import { Navigate, useSearchParams } from 'react-router-dom';

import api from '@/api';
import store from '@/reducers';
import { getUser } from '@/reducers/user';
import req from '@/utils/req';

const schema = {
  type: 'object',
  properties: {
    account: {
      title: '用户名',
      type: 'string',
      widget: 'input',
    },
    password: {
      title: '密码',
      type: 'string',
      widget: 'password',
      props: {
        type: 'password',
      },
    },
  },
};
const Login = () => {
  const form = useForm();
  const [URLSearchParams] = useSearchParams();
  const { loaded, login } = useSelector(
    ({ user }: RootState) => ({ loaded: user.loaded, login: user.login }),
    shallowEqual
  );

  const onFinish = async (formData: any) => {
    try {
      await req.post(api.sys.user.login, formData);
      store.dispatch(getUser());
    } catch (error) {
      console.error(error);
    }
  };
  if (loaded && login) {
    const redirect = URLSearchParams.get('redirect');
    if (redirect) {
      window.location.href = redirect;
      return;
    }
    return <Navigate to="/" />;
  }
  return (
    <FormRender
      widgets={{ password: Input.Password }}
      form={form}
      schema={schema}
      onFinish={onFinish}
      maxWidth={360}
      footer={true}
    />
  );
};

export default Login;
